package com.crazybytex.modbus.util;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 程序员潇然 crazybytex.com
 * 工具类 用来读取数据
 */
public class ByteStreamUtils {


    public static int readShort(InputStream in) throws IOException {
        int s = 0;
        int read = 0;
        for (int i = 0; i < 2; i++) {
            read = in.read();
            if (read < 0) {
                throw new IOException();
            }
            s = s << (8 * i) | read & 0xFF;
        }


        return s;
    }

    public static short readSignShort(InputStream in) throws IOException {
        byte[] bytes = new byte[2];
        in.read(bytes);

        return (short) (((bytes[0] & 0x00FF) << 8) | (0x00FF & bytes[1]));
    }


    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}
